package com.shigu.account.service;

import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.examples.MallWalletRecordExample;
import com.opentae.data.mall.interfaces.*;
import com.opentae.data.mall.pojo.CashDto;
import com.opentae.data.mall.pojo.MallUserDto;
import com.opentae.data.mall.pojo.MyInviteDto;
import com.shigu.MallResponse;
import com.shigu.PageResponse;
import com.shigu.account.enums.CashState;
import com.shigu.account.enums.MoneyRecordType;
import com.shigu.account.enums.VipLevel;
import com.shigu.account.exception.UtilsAccountException;
import com.shigu.account.vo.*;
import com.shigu.exceptions.AdminException;
import com.shigu.weixin.service.WxPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/*
 * create by  过儿  2019-05-06
 * 后台
 */
@Service
public class UserService {
    @Autowired
    ManagerMallUserMapper managerMallUserMapper;
    @Autowired
    CashApplyMapper cashApplyMapper;
    @Autowired
    WxPayService wxPayService;
    @Autowired
    MallWalletMapper mallWalletMapper;
    @Autowired
    MallWalletRecordMapper mallWalletRecordMapper;
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    UserWxInfoMapper userWxInfoMapper;
    @Autowired
    UserInviteInfoMapper userInviteInfoMapper;

    /**
     * @description 用户列表
     * @author 郭尔
     * @date 2019-05-06 16:15
     */
    public PageResponse<MallUserVo> mallUserList(Integer page, Integer size, String mallUserId,
                                                 String telephone, String nick, String wxNick, Integer userType,
                                                 Integer vipLevel, String agentId, String sortType,
                                                 String sortOrder) {
        String order = "";
        //处理排序问题
        if (StringUtils.isNotBlank(sortType) && StringUtils.isNotBlank(sortOrder)) {
            String type = "";
            switch (sortType) {
                case "inviteVipNum":
                    type = "c.invite_vip";
                    break;
                case "inviteNum":
                    type = "c.invite_num";
                    break;
                case "shareNum":
                    type = "c.invite_score";
                    break;
            }
            if (StringUtils.isNotBlank(type)) {
                order = type + " " + sortOrder;
            }

        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MallUserDto> list = managerMallUserMapper.userList((page - 1) * size, size, telephone,
                                                                   wxNick, nick, userType, vipLevel, mallUserId,
                                                                   agentId, order);
        int total = managerMallUserMapper.countUser(telephone, wxNick,nick, userType, vipLevel, mallUserId, agentId);
        PageResponse<MallUserVo> response = new PageResponse<>();
        response.setTotal(total);
        response.setData(list.stream().map(o -> {
            MallUserVo vo = new MallUserVo();
            vo.setUserId(o.getMallUserId());
            vo.setWxHeadUrl(o.getWxHeadUrl());
            vo.setVipLevel(o.getVipLevel());
            vo.setMallMoney(o.getMallMoney());
            vo.setTelephone(o.getTelephone());
            vo.setWxNick(o.getWxNick());
            vo.setNick(o.getNick());
            vo.setInviteVipNum(o.getInviteVipNum());
            vo.setInviteNum(o.getInviteNum());
            vo.setAgentId(o.getAgentId());
            vo.setShareNum(o.getShareNum());
            vo.setCreateTime(sdf.format(o.getCreateTime()));
            vo.setStaffNum(userInviteInfoMapper.countInviteUser(o.getMallUserId(), VipLevel.STAFF.getValue()));
            vo.setOwnerNum(userInviteInfoMapper.countInviteUser(o.getMallUserId(), VipLevel.OWNER.getValue()));
            vo.setBossNum(userInviteInfoMapper.countInviteUser(o.getMallUserId(), VipLevel.BOSS.getValue()));

            MallWallet wallet = mallWalletMapper.selByUserId(o.getMallUserId());
            if(wallet!=null){
                vo.setAchievement(wallet.getTotalReward().toString());
                vo.setVoucher(wallet.getVoucher().toString());
            }


            if (o.getAgentId() != null) {
                ManagerMallUser agent = managerMallUserMapper.selectByPrimaryKey(o.getAgentId());
                vo.setAgentNick(agent.getNick());
            }
            return vo;
        }).collect(Collectors.toList()));

        return response.success();
    }

    /**
     * @description 用户资金明细
     * @author 郭尔
     * @date 2019-05-06 17:14
     */
    public PageResponse<MoneyRecordVo> moneyRecord(Integer page, Integer size, String mallUserId) {
        MallWalletRecordExample example = new MallWalletRecordExample();
        example.createCriteria().andUserIdEqualTo(Long.valueOf(mallUserId));

        example.setStartIndex((page - 1) * size);
        example.setEndIndex(size);
        example.setOrderByClause("change_time desc");

        List<MallWalletRecord> list = mallWalletRecordMapper.selectByConditionList(example);
        int total = mallWalletRecordMapper.countByExample(example);
        PageResponse<MoneyRecordVo> response = new PageResponse<>();
        response.setTotal(total);
        response.setData(list.stream().map(o -> {
            MoneyRecordVo vo = new MoneyRecordVo();
            vo.setChangeTime(o.getChangeTime());
            vo.setMoney(o.getChangeValue());
            vo.setRemark(o.getRemark());
            return vo;
        }).collect(Collectors.toList()));

        return response.success();
    }

    /**
     * @description 提现列表
     * @author 郭尔
     * @date 2019-05-06 17:27
     */
    public PageResponse<WaitCashVo> waitCashList(Integer page, Integer size, String mallUserId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CashDto> list = cashApplyMapper.cashList((page - 1) * size, size, mallUserId, null);
        int total = cashApplyMapper.countCash(mallUserId, null);

        PageResponse<WaitCashVo> response = new PageResponse<>();
        response.setTotal(total);
        response.setData(list.stream().map(o -> {
            WaitCashVo vo = new WaitCashVo();
            vo.setApplyId(o.getApplyId());
            vo.setApplyTime(sdf.format(o.getApplyTime()));
            vo.setUserId(o.getMallUserId());
            vo.setNick(o.getNick());
            vo.setWxHeadUrl(o.getWxHeadUrl());
            vo.setWxNick(o.getWxNick());
            vo.setRemark(o.getReason());
            vo.setMoney(o.getMoney());
            return vo;
        }).collect(Collectors.toList()));
        return response.success();
    }

    /**
     * todo 定时
     * @param userId 执行人的id
     * @description 审核提现
     * @author 郭尔
     * @date 2019-05-06 18:05
     */
    public synchronized MallResponse examineCash(Long applyId, Boolean pass, String reason, Long userId) throws Exception {
        CashApply apply = cashApplyMapper.selectByPrimaryKey(applyId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        if (pass) {
            //先判断申请的状态
            if (apply.getStatus() == CashState.WAIT.getValue()) {
                String openIid = userWxInfoMapper.selAppOpeniid(apply.getMallUserId());
                String tradeoNo =  sdf.format(new Date())+apply.getApplyId().toString();
                //微信打款
                wxPayService.cashBack(openIid,tradeoNo, apply.getMoney(), "提现", "127.0.0.1");
                apply.setStatus(CashState.PASS.getValue());
            } else {
                throw new AdminException("该申请已审核过了");
            }
        } else {
            if (StringUtils.isBlank(reason)) {
                throw new AdminException("请输入拒绝理由");
            }
            //拒绝则返还回佣金
            userAccountService.addMoney(apply.getMallUserId(), apply.getMoney(), MoneyRecordType.refundCash.getText());
            apply.setStatus(CashState.REFUSE.getValue());
            apply.setReason(reason);
        }

        apply.setExamineTime(new Date());
        apply.setOperater(userId);
        cashApplyMapper.updateByPrimaryKeySelective(apply);
        return new MallResponse().success();
    }

    /**
     * status null 或者 2 3
     *
     * @description 提现审核记录
     * @author 郭尔
     * @date 2019-05-07 9:20
     */
    public PageResponse<CashRecordVo> cashRecord(Integer page, Integer size, String mallUserId, Integer status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CashDto> list = cashApplyMapper.cashList((page - 1) * size, size, mallUserId, status);
        int total = cashApplyMapper.countCash(mallUserId, status);

        PageResponse<CashRecordVo> response = new PageResponse<>();
        response.setTotal(total);
        response.setData(list.stream().map(o -> {
            CashRecordVo vo = new CashRecordVo();

            if (o.getExamineTime() != null) {
                vo.setExamineTime(sdf.format(o.getExamineTime()));
            }
            vo.setStatus(o.getStatus());
            vo.setApplyTime(sdf.format(o.getApplyTime()));
            vo.setUserId(o.getMallUserId());
            vo.setNick(o.getNick());
            vo.setWxHeadUrl(o.getWxHeadUrl());
            vo.setWxNick(o.getWxNick());
            vo.setRemark(o.getReason());
            vo.setMoney(o.getMoney());
            return vo;
        }).collect(Collectors.toList()));
        return response.success();
    }

    /**
     * @param type  0/null 查全部 1 普通 2会员
     * @description 查看用户邀请的人
     * @author 郭尔
     * @date 2019-07-05 16:51
     */
    public PageResponse<MyInviteVo> selMyInvite(Integer page, Integer size, Long mallUserId, Integer type){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MyInviteDto> list = userInviteInfoMapper.myInvite((page - 1) * size, size, mallUserId, type);
        int total = userInviteInfoMapper.countMyInvite(mallUserId, type);

        PageResponse<MyInviteVo> response = new PageResponse<>();
        response.setTotal(total);
        response.setHasNext(total>page*size);
        response.setData(list.stream().map(o->{
            MyInviteVo vo = new MyInviteVo();
            vo.setHeadUrl(o.getHeadUrl());
            vo.setUserName(o.getNick());
            vo.setTelephone(o.getTelephone());
            vo.setUserType(o.getVipLevel());
            vo.setWxHeadUrl(o.getWxHeadUrl());
            vo.setCreatedTime(sdf.format(o.getCreateTime()));
            vo.setWxNick(o.getWxNick());
            return vo;
        }).collect(Collectors.toList()));
        return response;
    }

    /**
     *
     * @description
     * @author 郭尔
     * @date 2019-07-06 10:14
     */
    public InviteNumVo getDiffInviteUserNum(Long mallUserId){
        int notVip = userInviteInfoMapper.countMyInvite(mallUserId, 1);
        int vipNum = userInviteInfoMapper.countMyInvite(mallUserId, 2);
        return new InviteNumVo(vipNum,notVip);
    }

    /**
     * @description 添加用户抵用券
     * @author 郭尔
     * @date 2019-11-12 16:01
     */
    public  MallResponse addUserVoucher(Long userId,String voucher) throws UtilsAccountException {
        userAccountService.addVoucher(userId,Double.valueOf(voucher),MoneyRecordType.voucher.getText());
        userAccountService.recordAddtionMoney(userId,2,Double.valueOf(voucher));
        return new MallResponse();
    }
}
